<template>
  <div class="admin-article-list">
    <div class="title">文章列表</div>
    <div class="search-wrapper">
      <div class="search-item-wrapper">
        <span class="select-name">类目：</span>
        <el-select v-model="searchForm.articleType" placeholder="请选择" id="type">
          <el-option v-for="item in articleTypes" :key="item.id"
            :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="search-item-wrapper">
        <span class="select-name">热门：</span>
        <el-select v-model="searchForm.isHot" placeholder="请选择" id="type">
          <el-option label="是" value="true"></el-option>
          <el-option label="否" value="false"></el-option>
        </el-select>
      </div>
      <div class="btn" @click="search">搜索</div>
      <div class="btn" @click="reset">重置</div>

      <div class="right" @click="$router.replace('/admin/add_article')">发表博文</div>
    </div>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column type="index" width="80" label="索引"></el-table-column>
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column prop="title" label="标题" min-width="200"></el-table-column>
      <el-table-column prop="type" label="类型" min-width="160"></el-table-column>
      <el-table-column prop="isHot" label="热门推荐" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isHot" active-color="#13ce66" inactive-color="#ff4949" @change="updateHotStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="isPublish" label="文章是否发布" width="140">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isPublish" active-color="#13ce66" inactive-color="#ff4949" @change="updatePublishStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="time" label="更新时间" min-width="180"></el-table-column>
      <el-table-column label="操作" min-width="160">
        <template slot-scope="scope">
          <el-button type="primary" plain size="small" @click="previewArticle(scope.row)">查看</el-button>
          <el-button type="warning" plain size="small" @click="updateArticle(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-wrapper">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currPage"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <el-dialog
      title="文章预览"
      :visible.sync="previewDialogVisible"
      width="60%"
      :before-close="handlePreviewDialogClose">
      <ArticleDetailCard :article="articleData" :coverImg="coverImg"/>
    </el-dialog>

    <el-dialog class="update-dialog"
      title="文章编辑"
      :visible.sync="updateDialogVisible"
      width="60%"
      :before-close="handleUpdateDialogClose">
      <UpdateArticleCard :articleForm="updateArticleData" @update="update"/>
    </el-dialog>
  </div>
</template>

<script>
import {baseUrl} from '../../api/index'
import ArticleDetailCard from "../../components/ArticleDetailCard";
import UpdateArticleCard from "../../components/UpdateArticleCard";
import deepClone from '../../assets/deepClone'
export default {
  name: "ArticleList",
  components: {
    ArticleDetailCard,
    UpdateArticleCard
  },
  data() {
    return {
      userInfo: {},  // 用户信息
      // 搜索
      searchForm: {
        articleType: '',
        isHot: ''
      },

      articleTypes: [],  // 文章类型列表

      // 表格数据
      tableData: [
        // {
        //   id: '1',
        //   title: '文章标题',
        //   type: '文章类型',
        //   intro: '文章简介',
        //   time: '2022-03-04',  // 文章更新时间
        //   isHot: false,  // 是否为热门推荐
        // }
      ],

      // 文章查看
      previewDialogVisible: false,
      articleData: {},  // 预览的文章数据
      coverImg: '',

      // 文章编辑
      updateDialogVisible: false,
      updateArticleData: {},

      // 分页
      currPage: 1,
      pageSize: 5,
      total: 0,  // 总博文数
    }
  },
  methods: {
    // 获取文章类型
    getArticleTypeList() {
      let token= this.userInfo.token;
      this.$http({
        url: '/admin/getTypeList',
        method: 'get',
        headers: {Authorization: token}
      }).then(response=>{
        let result= response.data;
        if(result.code===200) {
          let data= JSON.parse(result.data);
          this.articleTypes= data.data;
        } else {
          this.$message.warning('获取文章类型失败');
        }
      }).catch(e=>{
        this.$message.warning('获取文章类型失败');
      })
    },

    // 获取表格数据
    getTableData(currPage, pageSize) {
      let token= this.userInfo.token;
      this.$http({
        url: '/admin/getArticleList',
        method: 'get',
        params: {
          currPage,
          pageSize
        },
        headers: {Authorization: token}
      }).then(response=>{
        let result= response.data;
        if(result.code===200) {
          let data= result.data;
          this.tableData= JSON.parse(data.list);
          this.currPage= Number(data.currPage);
          this.pageSize= Number(data.pageSize);
          this.total= parseInt(data.total);
        } else {
          this.$message.warning('获取表格数据失败');
        }
      }).catch(e=>{
        this.$message.warning('获取表格数据失败');
      })
    },

    // 搜索
    search() {
      this.getSearchList(this.currPage, this.pageSize);
    },
    getSearchList(currPage, pageSize) {
      let token= this.userInfo.token;
      let {articleType, isHot} = this.searchForm;
      if(!articleType && !isHot) {
        this.$message.warning('请选择搜索条件');
        return;
      }
      let params= { currPage, pageSize };
      if(articleType) params.type= articleType;
      if(isHot) params.isHot= isHot;
      this.$http({
        url: '/admin/search',
        method: 'get',
        params: params,
        headers: {Authorization: token}
      }).then(response=>{
        let result= response.data;
        if(result.code===200) {
          let data= result.data;
          console.log(data);
          this.tableData= JSON.parse(data.list);
          console.log(this.tableData);
          this.currPage= Number(data.currPage);
          this.pageSize= Number(data.pageSize);
          this.total= parseInt(data.total);
        } else {
          this.$message.warning('获取表格数据失败');
        }
      }).catch(e=>{
        this.$message.warning('获取表格数据失败');
      })
    },
    reset() {
      this.searchForm.articleType= '';
      this.searchForm.isHot= '';
      this.getTableData(1,5);
    },


    // 表格操作
    // 切换热门推荐状态
    updateHotStatus(row) {
      let { id, isHot }= row;
      let token= this.userInfo.token;
      this.$http({
        url: '/admin/updateHotById',
        method: 'post',
        data: {
          id,
          isHot
        },
        headers: {Authorization: token}
      }).then(response=>{
        let result= response.data;
        if(result.code===200) {
          this.$message.success('热门推荐状态更新成功');
        } else {
          this.$message.warning('热门推荐状态更新失败');
          row.isHot= !row.isHot;
        }
      }).catch(e=>{
        this.$message.warning('热门推荐状态更新失败');
        row.isHot= !row.isHot;
      })
    },
    // 查看操作
    previewArticle(row) {
      this.previewDialogVisible= true;
      this.articleData= row;
      this.coverImg= baseUrl + this.articleData.coverImg;
    },
    handlePreviewDialogClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
          this.articleData= {};
          this.previewDialogVisible= false;
          this.coverImg= '';
        })
        .catch(_ => {});
    },
    // 文章编辑操作
    updateArticle(row) {
      this.updateDialogVisible= true;
      // 克隆对象，避免当该博文修改后但未提交而影响原有数据
      this.updateArticleData= deepClone(row);
    },
    update(value) {
      // console.log(value);
      this.getTableData(this.currPage, this.pageSize);
      this.updateArticleData= {};
      this.updateDialogVisible= false;
    },
    handleUpdateDialogClose() {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.updateArticleData= {};
          this.updateDialogVisible= false;
        })
        .catch(_ => {});
    },

    // 切换文章发布操作
    updatePublishStatus(row) {
      let { id, isPublish }= row;
      let token= this.userInfo.token;
      this.$http({
        url: '/admin/updatePublishById',
        method: 'post',
        data: {
          id,
          isPublish
        },
        headers: {Authorization: token}
      }).then(response=>{
        let result= response.data;
        if(result.code===200) {
          console.log(result);
          this.$message.success('文章发布状态更新成功');
        } else {
          this.$message.warning('文章发布状态更新失败');
          row.isPublish= !row.isPublish;
        }
      }).catch(e=>{
        this.$message.warning('文章发布状态更新失败');
        row.isPublish= !row.isPublish;
      })
    },


    // 分页器操作
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.currPage= 1;
      this.pageSize= val;
      if(this.searchForm.isHot || this.searchForm.articleType) {
        this.getSearchList(this.currPage, this.pageSize);
      } else {
        this.getTableData(this.currPage, this.pageSize);
      }
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currPage= val;
      if(this.searchForm.isHot || this.searchForm.articleType) {
        this.getSearchList(this.currPage, this.pageSize);
      } else {
        this.getTableData(this.currPage, this.pageSize);
      }
    }
  },
  mounted() {
    let userInfo= window.sessionStorage.getItem('userInfo');
    this.userInfo= JSON.parse(userInfo);
    this.getArticleTypeList();
    this.getTableData(1,5);

  }
}
</script>

<style scoped lang="less">
  .admin-article-list {
    .title {
      box-sizing: border-box;
      width: 100%;
      height: 50px;
      line-height: 40px;
      padding: 5px 10px;
      font-size: 24px;
      color: #fff;
      border-radius: 4px;
      background: #007BFF;
    }
    .search-wrapper {
      margin: 10px 0;
      .search-item-wrapper {
        float: left;
        display: flex;
        width: 300px;
        height: 40px;
        line-height: 40px;
        margin: 5px 10px;
        font-size: 16px;
      }
      .btn {
        display: inline-block;
        background: #63AEFF;
        text-align: center;
        color: #fff;
        border-radius: 4px;
        width: 80px;
        height: 30px;
        line-height: 30px;
        margin: 10px 10px;
        font-size: 18px;
        cursor: pointer;
      }

      .right {
        height: 40px;
        line-height: 40px;
        margin: 5px 10px;
        font-size: 16px;
        width: 100px;
        color: #fff;
        background: #DC3545;
        float: right;
        text-align: center;
        border-radius: 4px;
        cursor: pointer;
      }
    }

    .pagination-wrapper {
      margin-top: 40px;
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

  }


</style>
